package com.hxexp.weixin.mvc.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.hxexp.weixin.common.web.CookieUtil;
import com.hxexp.weixin.constant.CookieName;
import com.hxexp.weixin.constant.StringConstant;

/**
 * 应用版本参数拦截器
 *
 * <p>
 * 检查请求中是否有version参数，若存在version参数把参数值写入cookie
 * <p>
 * 在用户访问入口URL，需要使用该拦截器拦截请求, 在拦截时需要对URL做精确匹配
 *
 * @author li.jiang
 *
 */
public final class AppVersionInterceptor extends HandlerInterceptorAdapter {
    private static final int COOKIE_AGE = 0;
    /*
     * (non-Javadoc)
     *
     * @see org.springframework.web.servlet.handler.HandlerInterceptorAdapter#preHandle(javax.servlet.http.
     * HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object)
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        String version = request.getParameter(StringConstant.APP_VERSION_PARAM_NAME);

        if (!StringUtils.isEmpty(version)) {
            CookieUtil.addCookie(response, CookieName.APP_VERSION, version, COOKIE_AGE);
        }

        return super.preHandle(request, response, handler);
    }

}
